package io.gbznt.modules.buss.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.gbznt.common.utils.Constant;
import io.gbznt.common.utils.ShiroUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.apache.commons.lang.StringUtils;
import java.util.Map;
import io.gbznt.common.utils.PageUtils;
import io.gbznt.common.utils.Query;
import io.gbznt.modules.buss.dao.BussKnowledgeBaseDao;
import io.gbznt.modules.buss.entity.BussKnowledgeBaseEntity;
import io.gbznt.modules.buss.service.BussKnowledgeBaseService;
import io.gbznt.modules.sys.entity.SysDeptEntity;
import io.gbznt.modules.sys.service.SysDeptService;

@Service("bussKnowledgeBaseService")
public class BussKnowledgeBaseServiceImpl extends ServiceImpl<BussKnowledgeBaseDao, BussKnowledgeBaseEntity>
		implements BussKnowledgeBaseService {
	@Autowired
	private SysDeptService sysDeptService;

	@Override
	public PageUtils queryPage(Map<String, Object> params) {
		String menuId = (String) params.get("menuId");
		String leixing = (String) params.get("leixing");
		String name = (String) params.get("name");
		if (StringUtils.isBlank(leixing)) {
			leixing = 1 + "";
		}
		IPage<BussKnowledgeBaseEntity> page = this.page(new Query<BussKnowledgeBaseEntity>().getPage(params),
				new QueryWrapper<BussKnowledgeBaseEntity>()
						// .eq("type", 1)
						.eq(StringUtils.isNotEmpty(menuId) && !"1".equals(menuId), "menu_id", menuId)
						.eq(StringUtils.isNotEmpty(leixing), "type", leixing)
						.like(StringUtils.isNotEmpty(name), "name", name).orderByDesc("create_time")
						// 个人数据权限控制
						.in(!Constant.SUPER_ADMIN.equals(ShiroUtils.getUserId()),
								"dept_id", sysDeptService.getPermissionDeptIdsArr(true,true))
						.orderByDesc("create_time")
		);

		for (BussKnowledgeBaseEntity bbe : page.getRecords()) {
			if (StringUtils.isNotBlank(bbe.getMenuId())) {
				BussKnowledgeBaseEntity bb = this.getById(bbe.getMenuId());
				if (bb != null && StringUtils.isNotBlank(bb.getName())) {
					bbe.setMunuName(bb.getName());
				}
			}
			if (StringUtils.isNotBlank(bbe.getDeptId())) {
				SysDeptEntity dept = sysDeptService.getById(bbe.getDeptId());
				if (dept != null && StringUtils.isNotBlank(dept.getName())) {
					bbe.setDeptName(dept.getName());
				}
			}
		}
		return new PageUtils(page);
	}

}
